<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>动态棋谱</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
<script>
    tailwind.config = {
        theme: {
            extend: {
                colors: {
                    primary: '#8B4513',
                    secondary: '#D2B48C',
                    board: '#F5DEB3',
                    accent: '#CD5C5C',
                },
                fontFamily: {
                    inter: ['Inter', 'sans-serif'],
                },
            }
        }
    }
</script>
<style type="text/tailwindcss">
    @layer utilities {
            .chess-shadow {
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.2);
            }
            .board-grid {
                background-image: 
                  linear-gradient(to right, #8B4513 1px, transparent 1px),
                  linear-gradient(to bottom, #8B4513 1px, transparent 1px);
                background-size: 50px 100%, 100% 50px;
                background-position: 50px 0, 0 50px;
            }
            .piece-transition {
                transition: transform 0.3s ease-in-out;
            }
            .highlight {
                animation: pulse 2s infinite;
            }
            @keyframes pulse {
                0% {
                    box-shadow: 0 0 0 0 rgba(205, 92, 92, 0.7);
                }
                70% {
                    box-shadow: 0 0 0 10px rgba(205, 92, 92, 0);
                }
                100% {
                    box-shadow: 0 0 0 0 rgba(205, 92, 92, 0);
                }
            }
        }
    </style>
    <style>
    .chessbox-piece {
        width: 44px;
        height: 44px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        font-size: 1.2rem;
        margin: 2px;
        cursor: pointer;
        border: 2px solid transparent;
        transition: border 0.2s;
        user-select: none;
    }
    .chessbox-piece[data-color="red"] {
        background: #e53e3e;
        color: #fff;
    }
    .chessbox-piece[data-color="black"] {
        background: #222;
        color: #fff;
    }
    .chessbox-piece.selected {
        border: 2px solid #38bdf8;
        box-shadow: 0 0 0 2px #38bdf8;
    }
    .box-cell {
        width: 44px;
        height: 44px;
        border: 2px solid #bbb;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #fff;
        cursor: pointer;
        position: relative;
        transition: border 0.2s;
    }
    .box-cell.selected {
        border: 2px solid #38bdf8;
        box-shadow: 0 0 0 2px #38bdf8;
    }
    .box-piece {
        width: 38px;
        height: 38px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        font-size: 1.1rem;
        user-select: none;
    }
    .box-piece.red {
        background: #e53e3e;
        color: #fff;
    }
    .box-piece.black {
        background: #222;
        color: #fff;
    }
</style>
</head>

<body class="bg-gray-100 font-inter min-h-screen">
    <div class="container mx-auto px-4 py-8">
        <header class="text-center mb-8">
            <h1 class="text-[clamp(1.8rem,5vw,3rem)] font-bold text-primary mb-2">中国象棋棋谱记录</h1>
            <p class="text-gray-600 max-w-2xl mx-auto">点击棋子和目标格，记录每一步走法，支持撤销和导出</p>
        </header>

        <div class="flex flex-col lg:flex-row items-start w-full max-w-5xl mx-auto">
            <!-- 棋子收纳盘区 -->
            <div class="flex flex-col gap-8 items-center mr-8">
                <div>
                    <h3 class="text-lg font-semibold text-gray-800 mb-2 text-center">黑方棋盒</h3>
                    <div id="blackBox" class="grid grid-cols-4 grid-rows-4 gap-1 bg-gray-200 p-2 rounded-lg">
                        <!-- 动态生成16格 -->
                    </div>
                </div>
                <div>
                    <h3 class="text-lg font-semibold text-red-700 mb-2 text-center">红方棋盒</h3>
                    <div id="redBox" class="grid grid-cols-4 grid-rows-4 gap-1 bg-gray-200 p-2 rounded-lg">
                        <!-- 动态生成16格 -->
                    </div>
                </div>
            </div>
            <div class="flex-1 flex flex-col items-center">
            <!-- 自定义摆棋区 -->
            <div class="flex flex-wrap items-center gap-4 mb-4 w-full max-w-2xl justify-center">
                <div class="flex items-center gap-2">
                    <label class="font-medium text-gray-700">棋子类型:</label>
                    <select id="customPieceType" class="p-2 border border-gray-300 rounded-md">
                        <option value="r">车</option>
                        <option value="n">马</option>
                        <option value="b">相/象</option>
                        <option value="a">仕/士</option>
                        <option value="k">帅/将</option>
                        <option value="c">炮</option>
                        <option value="p">兵/卒</option>
                    </select>
                </div>
                <div class="flex items-center gap-2">
                    <label class="font-medium text-gray-700">颜色:</label>
                    <select id="customPieceColor" class="p-2 border border-gray-300 rounded-md">
                        <option value="red">红</option>
                        <option value="black">黑</option>
                    </select>
                </div>
                <button id="clearBoardBtn" class="px-4 py-2 bg-gray-200 hover:bg-gray-300 rounded-md font-medium">清空棋盘</button>
                <button id="saveInitBtn" class="px-4 py-2 bg-blue-600 text-white rounded-md font-medium hover:bg-blue-700 transition-colors">保存初始布局</button>
                <button id="startRecordBtn" class="px-4 py-2 bg-green-600 text-white rounded-md font-medium hover:bg-green-700 transition-colors">开始</button>
            </div>
            <textarea id="initExportArea" class="w-full max-w-2xl mt-2 p-2 border border-gray-300 rounded-md text-sm text-gray-700 hidden" rows="4" readonly></textarea>
            <!-- 棋盘区域 -->
            <div class="bg-white rounded-xl shadow-lg p-4 lg:p-6 relative overflow-hidden mb-8">
                <!-- 黑方编号（上方，1-9） -->
                <div class="w-[450px] flex justify-between mx-auto mb-6">
                    <span class="flex-1 text-center font-bold text-xl text-gray-700 select-none">1</span>
                    <span class="flex-1 text-center font-bold text-xl text-gray-700 select-none">2</span>
                    <span class="flex-1 text-center font-bold text-xl text-gray-700 select-none">3</span>
                    <span class="flex-1 text-center font-bold text-xl text-gray-700 select-none">4</span>
                    <span class="flex-1 text-center font-bold text-xl text-gray-700 select-none">5</span>
                    <span class="flex-1 text-center font-bold text-xl text-gray-700 select-none">6</span>
                    <span class="flex-1 text-center font-bold text-xl text-gray-700 select-none">7</span>
                    <span class="flex-1 text-center font-bold text-xl text-gray-700 select-none">8</span>
                    <span class="flex-1 text-center font-bold text-xl text-gray-700 select-none">9</span>
                </div>
                <div id="boardContainer"
                    class="relative mx-auto aspect-square w-[450px] bg-board rounded-lg board-grid border-2 border-[#8B4513]">
                    <!-- 棋盘将在这里动态生成 -->
                    <div id="riverLineMask"
                        style="
                            position: absolute;
                            left: 0;
                            width: 100%;
                            height: 48px;
                            top: 201px;
                            background: #F5DEB3;
                            z-index: 1;
                            pointer-events: none;
                        "></div>
                    <div id="riverText" style="
                            position: absolute;
                            left: 0;
                            width: 100%;
                            top: 50%;
                            transform: translateY(-50%);
                            text-align: center;
                            font-size: 2rem;
                            color: #8B4513;
                            letter-spacing: 2rem;
                            font-weight: bold;
                            opacity: 0.25;
                            pointer-events: none;
                            z-index: 1;
                            user-select: none;
                        ">
                        楚河 汉界
                    </div>
                </div>
                <!-- 红方编号（下方，九到一） -->
                <div class="w-[450px] flex justify-between mx-auto mt-6">
                    <span class="flex-1 text-center font-bold text-xl text-red-700 select-none">九</span>
                    <span class="flex-1 text-center font-bold text-xl text-red-700 select-none">八</span>
                    <span class="flex-1 text-center font-bold text-xl text-red-700 select-none">七</span>
                    <span class="flex-1 text-center font-bold text-xl text-red-700 select-none">六</span>
                    <span class="flex-1 text-center font-bold text-xl text-red-700 select-none">五</span>
                    <span class="flex-1 text-center font-bold text-xl text-red-700 select-none">四</span>
                    <span class="flex-1 text-center font-bold text-xl text-red-700 select-none">三</span>
                    <span class="flex-1 text-center font-bold text-xl text-red-700 select-none">二</span>
                    <span class="flex-1 text-center font-bold text-xl text-red-700 select-none">一</span>
                </div>
            </div>

            <!-- 走法记录区域 -->
            <div class="bg-white rounded-xl shadow-lg p-6 w-full max-w-2xl">
                <h2 class="text-xl font-semibold text-gray-800 mb-4">走法记录</h2>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead>
                            <tr>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">步数</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">红方</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">黑方</th>
                            </tr>
                        </thead>
                        <tbody id="moveRecordBody" class="bg-white divide-y divide-gray-200">
                            <!-- 走法历史将在这里动态生成 -->
                        </tbody>
                    </table>
                </div>
                <div class="mt-4 flex gap-2">
                    <button id="undoMoveBtn" class="px-4 py-2 bg-yellow-500 text-white rounded hover:bg-yellow-600 transition-colors">撤销</button>
                    <button id="resetMoveBtn" class="px-4 py-2 bg-gray-300 text-gray-800 rounded hover:bg-gray-400 transition-colors">重置</button>
                    <button id="exportMoveBtn" class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 transition-colors ml-auto">导出棋谱</button>
                </div>
                <textarea id="exportMoveArea" class="w-full mt-4 p-2 border border-gray-300 rounded-md text-sm text-gray-700 hidden" rows="4" readonly></textarea>
            </div>
        </div>

        <footer class="mt-12 text-center text-gray-500 text-sm">
            <p>© 2025 中国象棋棋谱记录 | 使用 HTML, CSS 和 JavaScript 构建</p>
        </footer>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // 常量定义 - 中国象棋标准棋盘（9列10行）
            const BOARD_SIZE = 8; // 横向9个点
            const BOARD_HEIGHT = 9; // 纵向9个点
            const CELL_SIZE = 50; // 每个格子的大小 (px)
            const PIECE_SIZE = 44; // 棋子大小 (px)

            // 设置棋盘容器宽高，和 index.html 保持一致
            const boardContainer = document.getElementById('boardContainer');
            boardContainer.style.width = `${CELL_SIZE * BOARD_SIZE}px`;
            boardContainer.style.height = `${CELL_SIZE * BOARD_HEIGHT}px`;
            boardContainer.style.backgroundSize = `${CELL_SIZE}px ${CELL_SIZE}px`;

            // 状态变量
            let moveRecord = [];
            let moveRecordStep = 0;
            let moveRecordIsRedTurn = true;
            let moveRecordSelectedPiece = null;
            let isRecording = false;

            const moveRecordBody = document.getElementById('moveRecordBody');
            const undoMoveBtn = document.getElementById('undoMoveBtn');
            const resetMoveBtn = document.getElementById('resetMoveBtn');
            const exportMoveBtn = document.getElementById('exportMoveBtn');
            const exportMoveArea = document.getElementById('exportMoveArea');
            const startRecordBtn = document.getElementById('startRecordBtn');

            // 棋子类型映射
            const pieceSymbols = {
                chineseChess: {
                    r: { red: '車', black: '車' },
                    n: { red: '馬', black: '馬' },
                    b: { red: '相', black: '象' },
                    a: { red: '仕', black: '士' },
                    k: { red: '帥', black: '將' },
                    c: { red: '炮', black: '炮' },
                    p: { red: '兵', black: '卒' }
                }
            };

            // 监听棋盘点击
            boardContainer.addEventListener('click', function(e) {
                const rect = boardContainer.getBoundingClientRect();
                const x = Math.round((e.clientX - rect.left) / CELL_SIZE);
                const y = Math.round((e.clientY - rect.top) / CELL_SIZE);
                if (x >= 0 && x <= 8 && y >= 0 && y <= 9) {
                    onMoveRecordCellClick(x, y);
                }
            });

            function onMoveRecordCellClick(x, y) {
                // 查找当前棋子
                const pieceEl = Array.from(boardContainer.children).find(el => el.dataset && el.dataset.x == x && el.dataset.y == y && el.classList.contains('absolute'));
                if (moveRecordSelectedPiece) {
                    // 不能走到自己已有棋子的格子
                    if (!pieceEl || pieceEl.dataset.color !== moveRecordSelectedPiece.dataset.color) {
                        // 记录走法
                        moveRecord = moveRecord.slice(0, moveRecordStep);
                        moveRecord.push({
                            from: { x: parseInt(moveRecordSelectedPiece.dataset.x), y: parseInt(moveRecordSelectedPiece.dataset.y) },
                            to: { x, y },
                            piece: moveRecordSelectedPiece.dataset.type,
                            color: moveRecordSelectedPiece.dataset.color,
                            captured: pieceEl ? {
                                type: pieceEl.dataset.type,
                                color: pieceEl.dataset.color,
                                x: parseInt(pieceEl.dataset.x),
                                y: parseInt(pieceEl.dataset.y)
                            } : null,
                            isRedTurn: moveRecordIsRedTurn
                        });
                        moveRecordStep++;
                        // 执行移动
                        if (pieceEl) pieceEl.remove();
                        moveRecordSelectedPiece.style.left = `${x * CELL_SIZE - PIECE_SIZE / 2}px`;
                        moveRecordSelectedPiece.style.top = `${y * CELL_SIZE - PIECE_SIZE / 2}px`;
                        moveRecordSelectedPiece.dataset.x = x;
                        moveRecordSelectedPiece.dataset.y = y;
                        moveRecordIsRedTurn = !moveRecordIsRedTurn;
                        moveRecordSelectedPiece = null;
                        renderMoveRecordList();
                    } else {
                        // 选中同色棋子，切换高亮
                        moveRecordSelectedPiece = pieceEl;
                    }
                } else if (pieceEl && ((moveRecordIsRedTurn && pieceEl.dataset.color === 'red') || (!moveRecordIsRedTurn && pieceEl.dataset.color === 'black'))) {
                    // 只高亮选中，不做移动
                    moveRecordSelectedPiece = pieceEl;
                }
                // 高亮
                Array.from(boardContainer.children).forEach(el => el.classList.remove('highlight'));
                if (moveRecordSelectedPiece) moveRecordSelectedPiece.classList.add('highlight');
            }

            function renderMoveRecordList() {
                moveRecordBody.innerHTML = '';
                let step = 1;
                for (let i = 0; i < moveRecord.length; i += 2) {
                    const tr = document.createElement('tr');
                    const tdStep = document.createElement('td');
                    tdStep.className = 'px-4 py-2 whitespace-nowrap text-sm font-medium text-gray-900';
                    tdStep.textContent = step++;
                    tr.appendChild(tdStep);
                    const tdRed = document.createElement('td');
                    tdRed.className = 'px-4 py-2 whitespace-nowrap text-sm text-gray-700';
                    tdRed.textContent = moveRecord[i]?.color === 'red' ? getMoveRecordNotation(moveRecord[i]) : '';
                    tr.appendChild(tdRed);
                    const tdBlack = document.createElement('td');
                    tdBlack.className = 'px-4 py-2 whitespace-nowrap text-sm text-gray-700';
                    tdBlack.textContent = moveRecord[i+1]?.color === 'black' ? getMoveRecordNotation(moveRecord[i+1]) : '';
                    tr.appendChild(tdBlack);
                    moveRecordBody.appendChild(tr);
                }
            }

            function getMoveRecordNotation(move) {
                const pieceName = pieceSymbols.chineseChess[move.piece][move.color];
                return `${pieceName} (${move.from.x+1},${10-move.from.y})→(${move.to.x+1},${10-move.to.y})`;
            }

            undoMoveBtn.addEventListener('click', function() {
                if (moveRecordStep === 0) return;
                moveRecordStep--;
                const move = moveRecord[moveRecordStep];
                // 恢复棋子位置
                const pieceEl = Array.from(boardContainer.children).find(el => el.dataset && el.dataset.type === move.piece && el.dataset.color === move.color && el.dataset.x == move.to.x && el.dataset.y == move.to.y);
                if (pieceEl) {
                    pieceEl.style.left = `${move.from.x * CELL_SIZE - PIECE_SIZE / 2}px`;
                    pieceEl.style.top = `${move.from.y * CELL_SIZE - PIECE_SIZE / 2}px`;
                    pieceEl.dataset.x = move.from.x;
                    pieceEl.dataset.y = move.from.y;
                }
                // 恢复被吃的棋子
                if (move.captured) {
                    const captured = document.createElement('div');
                    const colorClass = move.captured.color === 'red' ? 'bg-red-600 text-white' : 'bg-gray-800 text-white';
                    captured.className = `absolute w-[${PIECE_SIZE}px] h-[${PIECE_SIZE}px] rounded-full flex items-center justify-center font-bold text-xl ${colorClass} chess-shadow piece-transition cursor-pointer`;
                    captured.style.left = `${move.captured.x * CELL_SIZE - PIECE_SIZE / 2}px`;
                    captured.style.top = `${move.captured.y * CELL_SIZE - PIECE_SIZE / 2}px`;
                    captured.style.zIndex = 100;
                    captured.dataset.id = `${move.captured.type}-${move.captured.x}-${move.captured.y}`;
                    captured.dataset.type = move.captured.type;
                    captured.dataset.color = move.captured.color;
                    captured.dataset.x = move.captured.x;
                    captured.dataset.y = move.captured.y;
                    captured.textContent = pieceSymbols.chineseChess[move.captured.type][move.captured.color];
                    boardContainer.appendChild(captured);
                }
                moveRecordIsRedTurn = move.isRedTurn;
                moveRecord = moveRecord.slice(0, moveRecordStep);
                renderMoveRecordList();
            });

            resetMoveBtn.addEventListener('click', function() {
                location.reload();
            });

            exportMoveBtn.addEventListener('click', function() {
                // 导出为标准moves数组格式
                const moves = moveRecord.map(move => ({
                    from: move.from,
                    to: move.to,
                    piece: move.piece,
                    color: move.color,
                    notation: getMoveRecordNotation(move)
                }));
                exportMoveArea.value = JSON.stringify(moves, null, 2);
                exportMoveArea.classList.remove('hidden');
                exportMoveArea.select();
                document.execCommand('copy');
                exportMoveBtn.textContent = '已复制到剪贴板!';
                setTimeout(() => {
                    exportMoveBtn.textContent = '导出棋谱';
                }, 1500);
            });

            // 自定义摆棋功能
            const customPieceType = document.getElementById('customPieceType');
            const customPieceColor = document.getElementById('customPieceColor');
            const clearBoardBtn = document.getElementById('clearBoardBtn');
            const saveInitBtn = document.getElementById('saveInitBtn');
            const initExportArea = document.getElementById('initExportArea');

            // 棋盘数据结构
            let customPieces = [];

            // 初始化空棋盘
            function renderCustomBoard() {
                // 清空棋盘上的所有棋子
                Array.from(boardContainer.children).forEach(child => {
                    if (child.id !== 'riverText' && child.id !== 'riverLineMask') {
                        boardContainer.removeChild(child);
                    }
                });
                // 渲染自定义棋子
                customPieces.forEach(piece => {
                    renderCustomPiece(piece);
                });
            }

            function renderCustomPiece(piece) {
                const symbolMap = {
                    r: { red: '車', black: '車' },
                    n: { red: '馬', black: '馬' },
                    b: { red: '相', black: '象' },
                    a: { red: '仕', black: '士' },
                    k: { red: '帥', black: '將' },
                    c: { red: '炮', black: '炮' },
                    p: { red: '兵', black: '卒' }
                };
                const symbol = symbolMap[piece.type][piece.color];
                const colorClass = piece.color === 'red' ? 'bg-red-600 text-white' : 'bg-gray-800 text-white';
                const pieceElement = document.createElement('div');
                pieceElement.className = `absolute w-[44px] h-[44px] rounded-full flex items-center justify-center font-bold text-xl ${colorClass} chess-shadow piece-transition cursor-pointer`;
                pieceElement.style.left = `${piece.x * 50 - 22}px`;
                pieceElement.style.top = `${piece.y * 50 - 22}px`;
                pieceElement.style.zIndex = 100;
                pieceElement.dataset.type = piece.type;
                pieceElement.dataset.color = piece.color;
                pieceElement.dataset.x = piece.x;
                pieceElement.dataset.y = piece.y;
                pieceElement.textContent = symbol;
                // 点击棋子可移除
                pieceElement.addEventListener('click', (e) => {
                    e.stopPropagation();
                    customPieces = customPieces.filter(p => !(p.x === piece.x && p.y === piece.y));
                    renderCustomBoard();
                });
                boardContainer.appendChild(pieceElement);
            }

            // 棋盒交互
            let chessboxSelected = null;
            document.querySelectorAll('.chessbox-piece').forEach(btn => {
                btn.addEventListener('click', function(e) {
                    if (isRecording) return;
                    document.querySelectorAll('.chessbox-piece').forEach(b => b.classList.remove('selected'));
                    btn.classList.add('selected');
                    chessboxSelected = { type: btn.dataset.type, color: btn.dataset.color };
                });
            });

            // 棋子收纳盘数据
            const initialBoxPieces = {
                red: [
                    { type: 'r', color: 'red' }, { type: 'n', color: 'red' }, { type: 'b', color: 'red' }, { type: 'a', color: 'red' },
                    { type: 'k', color: 'red' }, { type: 'a', color: 'red' }, { type: 'b', color: 'red' }, { type: 'n', color: 'red' },
                    { type: 'r', color: 'red' }, { type: 'c', color: 'red' }, { type: 'c', color: 'red' },
                    { type: 'p', color: 'red' }, { type: 'p', color: 'red' }, { type: 'p', color: 'red' }, { type: 'p', color: 'red' }, { type: 'p', color: 'red' }
                ],
                black: [
                    { type: 'r', color: 'black' }, { type: 'n', color: 'black' }, { type: 'b', color: 'black' }, { type: 'a', color: 'black' },
                    { type: 'k', color: 'black' }, { type: 'a', color: 'black' }, { type: 'b', color: 'black' }, { type: 'n', color: 'black' },
                    { type: 'r', color: 'black' }, { type: 'c', color: 'black' }, { type: 'c', color: 'black' },
                    { type: 'p', color: 'black' }, { type: 'p', color: 'black' }, { type: 'p', color: 'black' }, { type: 'p', color: 'black' }, { type: 'p', color: 'black' }
                ]
            };
            let boxPieces = {
                red: Array.from(initialBoxPieces.red),
                black: Array.from(initialBoxPieces.black)
            };
            let boxSelected = null; // {type, color, box, idx}

            function renderBox() {
                const redBox = document.getElementById('redBox');
                const blackBox = document.getElementById('blackBox');
                redBox.innerHTML = '';
                blackBox.innerHTML = '';
                for (let i = 0; i < 16; i++) {
                    // 红
                    const cellR = document.createElement('div');
                    cellR.className = 'box-cell' + (boxSelected && boxSelected.box === 'red' && boxSelected.idx === i ? ' selected' : '');
                    if (boxPieces.red[i]) {
                        const p = boxPieces.red[i];
                        cellR.innerHTML = `<div class="box-piece red">${pieceSymbols.chineseChess[p.type].red}</div>`;
                        cellR.addEventListener('click', () => {
                            boxSelected = { ...p, box: 'red', idx: i };
                            renderBox();
                        });
                    } else {
                        cellR.addEventListener('click', () => {
                            boxSelected = null;
                            renderBox();
                        });
                    }
                    redBox.appendChild(cellR);
                    // 黑
                    const cellB = document.createElement('div');
                    cellB.className = 'box-cell' + (boxSelected && boxSelected.box === 'black' && boxSelected.idx === i ? ' selected' : '');
                    if (boxPieces.black[i]) {
                        const p = boxPieces.black[i];
                        cellB.innerHTML = `<div class="box-piece black">${pieceSymbols.chineseChess[p.type].black}</div>`;
                        cellB.addEventListener('click', () => {
                            boxSelected = { ...p, box: 'black', idx: i };
                            renderBox();
                        });
                    } else {
                        cellB.addEventListener('click', () => {
                            boxSelected = null;
                            renderBox();
                        });
                    }
                    blackBox.appendChild(cellB);
                }
            }

            // 棋盘点击放置棋盒选中棋子
            boardContainer.addEventListener('click', function(e) {
                if (isRecording) return;
                const rect = boardContainer.getBoundingClientRect();
                const x = Math.round((e.clientX - rect.left) / 50);
                const y = Math.round((e.clientY - rect.top) / 50);
                if (x < 0 || x > 8 || y < 0 || y > 9) return;
                // 检查该位置是否已有棋子
                const exist = customPieces.find(p => p.x === x && p.y === y);
                if (boxSelected) {
                    if (!exist) {
                        customPieces.push({
                            type: boxSelected.type,
                            color: boxSelected.color,
                            x, y
                        });
                        // 从收纳盘移除
                        boxPieces[boxSelected.box][boxSelected.idx] = null;
                        boxSelected = null;
                        renderCustomBoard();
                        renderBox();
                    }
                    return;
                }
                // 兼容原有点击移除：移除棋盘棋子并回收到收纳盘
                if (exist) {
                    // 找到收纳盘第一个空位
                    const arr = boxPieces[exist.color];
                    const idx = arr.findIndex(x => !x);
                    if (idx !== -1) {
                        arr[idx] = { type: exist.type, color: exist.color };
                        customPieces = customPieces.filter(p => !(p.x === x && p.y === y));
                        renderCustomBoard();
                        renderBox();
                    }
                }
            }, true);

            clearBoardBtn.addEventListener('click', function() {
                if (isRecording) return;
                customPieces.forEach(p => {
                    const arr = boxPieces[p.color];
                    const idx = arr.findIndex(x => !x);
                    if (idx !== -1) arr[idx] = { type: p.type, color: p.color };
                });
                customPieces = [];
                renderCustomBoard();
                renderBox();
            });

            saveInitBtn.addEventListener('click', function() {
                if (isRecording) return;
                const data = JSON.stringify(customPieces);
                initExportArea.value = data;
                initExportArea.classList.remove('hidden');
                initExportArea.select();
                document.execCommand('copy');
                saveInitBtn.textContent = '已复制!';
                setTimeout(() => {
                    saveInitBtn.textContent = '保存初始布局';
                }, 1500);
            });

            startRecordBtn.addEventListener('click', function() {
                if (isRecording) return;
                isRecording = true;
                // 禁用自定义摆棋相关控件
                customPieceType.disabled = true;
                customPieceColor.disabled = true;
                clearBoardBtn.disabled = true;
                saveInitBtn.disabled = true;
                startRecordBtn.disabled = true;
                startRecordBtn.textContent = '已开始';
                document.getElementById('redBox').style.opacity = 0.5;
                document.getElementById('blackBox').style.opacity = 0.5;
                // 清空棋盘上所有自定义棋子
                Array.from(boardContainer.children).forEach(child => {
                    if (child.classList && child.classList.contains('absolute')) {
                        boardContainer.removeChild(child);
                    }
                });
                // 用customPieces渲染为走子记录用的棋子（不绑定任何点击事件）
                customPieces.forEach(piece => {
                    const symbol = pieceSymbols.chineseChess[piece.type][piece.color];
                    const colorClass = piece.color === 'red' ? 'bg-red-600 text-white' : 'bg-gray-800 text-white';
                    const pieceElement = document.createElement('div');
                    pieceElement.className = `absolute w-[44px] h-[44px] rounded-full flex items-center justify-center font-bold text-xl ${colorClass} chess-shadow piece-transition cursor-pointer`;
                    pieceElement.style.left = `${piece.x * 50 - 22}px`;
                    pieceElement.style.top = `${piece.y * 50 - 22}px`;
                    pieceElement.style.zIndex = 100;
                    pieceElement.dataset.type = piece.type;
                    pieceElement.dataset.color = piece.color;
                    pieceElement.dataset.x = piece.x;
                    pieceElement.dataset.y = piece.y;
                    pieceElement.textContent = symbol;
                    // 不绑定任何点击事件
                    boardContainer.appendChild(pieceElement);
                });
                // 清空自定义数据，后续只用走子记录
                customPieces = [];
            });

            // 初始渲染
            renderCustomBoard();
            renderBox();
        });
    </script>

</body>

</html>